易理解版八皇后
为了面试复习一下经典的题目
八皇后
当然有更短更精奇的写法,但是我觉得我这个比较容易理解吧?。。。
1 count = 0 2 3 4 def eight_queens(queens_position, depth): 5 """ 6 Computer how many solutions are there for eight queens problem 7 """ 8 9 def is_valid(board, pos): 10 """ 11 Check if given position is valid 12 """ 13 14 def isOnSameLine(pos1, pos2): 15 """ 16 check if this two position is on diagonal or vertical line 17 """ 18 if pos1[1] == pos2[1]: 19 return True 20 21 # Slope is 1 22 # y = (x - a) + b 23 if pos2[1] == (pos2[0] - pos1[0] + pos1[1]): 24 return True 25 26 # Slope is -1 27 # y = -(x - a) + b 28 if pos2[1] == (-(pos2[0] - pos1[0]) + pos1[1]): 29 return True 30 31 return False 32 33 for lop in range(len(board)): 34 if isOnSameLine((lop, board[lop]), pos): 35 return False 36 return True 37 38 if depth == 8: 39 print(queens_position) 40 global count 41 count += 1 42 return 43 44 # Trying to place queen 45 for lop in range(8): 46 if is_valid(queens_position, (len(queens_position), lop)): 47 tmp_list = list(queens_position) 48 tmp_list.append(lop) 49 eight_queens(tmp_list, depth + 1) 50 51 52 if __name__ == '__main__': 53 eight_queens([], 0) 54 print(count)